/*
 * @Author: Swance
 * @Date: 2023-12-19
 * @Description: 图层插件
 */

import { fabric } from 'fabric';
import { IEditor } from '@/types/global';
import { BoardSyncEvent, JsonOption } from '@/utils/Const.ts';

class LayerPlugin {
  canvas: fabric.Canvas;
  editor: IEditor;
  static pluginName: string = 'LayerPlugin';
  static apis: string[] = ['up', 'down'];
  constructor(canvas: fabric.Canvas, editor: IEditor) {
    this.canvas = canvas;
    this.editor = editor;
  }

  // 元素置于顶层
  up(activeObject: fabric.Object) {
    this.canvas.bringToFront(activeObject);
    this.editor.emit(BoardSyncEvent.UP, {
      isNewAction: true,
      oldElements: [activeObject.toJSON(JsonOption)],
    });
  }

  // 元素置于底层
  down(activeObject: fabric.Object) {
    this.canvas.sendToBack(activeObject);
    this.editor.emit(BoardSyncEvent.DOWN, {
      isNewAction: true,
      oldElements: [activeObject.toJSON(JsonOption)],
    });
  }

  // 右键菜单回调
  contextMenu() {
    const activeObject = this.canvas.getActiveObject();
    if (!activeObject) return;
    return [
      {
        text: '置于顶层',
        disabled: false,
        onclick: () => this.up(activeObject),
      },
      {
        text: '置于底层',
        disabled: false,
        onclick: () => this.down(activeObject),
      },
    ];
  }
}

export default LayerPlugin;
